package xyz.xpman.prisonerfitness.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.Switch;
import android.widget.TextView;

import androidx.annotation.RequiresApi;

import org.jetbrains.annotations.NotNull;

import java.text.MessageFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import xyz.xpman.prisonerfitness.R;
import xyz.xpman.prisonerfitness.activity.base.BaseActivity;
import xyz.xpman.prisonerfitness.config.Constant;
import xyz.xpman.prisonerfitness.entity.Mappings;
import xyz.xpman.prisonerfitness.entity.Moves;
import xyz.xpman.prisonerfitness.entity.TrainingRecord;
import xyz.xpman.prisonerfitness.entity.TrainingStandard;
import xyz.xpman.prisonerfitness.service.TrainingRecordService;
import xyz.xpman.prisonerfitness.util.ToastUtil;

@SuppressLint("UseCompatLoadingForDrawables")
public class TrainingFinishActivity extends BaseActivity {
    private final Map<Integer, TrainingDifficulty> difficultyMapping = new HashMap<>(3);

    // 0: easy; 1: neutral; 2: difficult;
    private TrainingDifficulty trainingDifficulty;

    private Moves move;
    private int usedTime;
    private TrainingStandard.Standard standard;

    private ImageView movesFlagImg;
    private ImageView trainingSatisfied;
    private ImageView trainingNeutral;
    private ImageView trainingDissatisfied;

    private TextView movesName;
    private TextView trainingPart;
    private TextView trainingThoughts;
    private TextView trainingUsedTime;
    private TextView trainingTotalTimes;
    private TextView trainingTotalGroups;

    @SuppressLint("UseSwitchCompatOrMaterialCode")
    private Switch isWarmUpTraining;


    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        hideTitleBar();
        setContentView(R.layout.activity_training_finish);

        initData();
        initTrainingDifficultyData();
        initView();
        renderView();
        initEvent();
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    private void initData() {
        final String id = getIntentExtra(Constant.EXTRA_MOVES_ID);

        move = Mappings.getMove(id);
        standard = getIntentExtra(Constant.EXTRA_STANDARD);
        usedTime = getIntentExtra(Constant.EXTRA_USED_TIME);
    }

    private void initTrainingDifficultyData() {
        final Resources res = getResources();

        TrainingDifficulty nature = TrainingDifficulty.nature();
        nature.drawable = res.getDrawable(R.drawable.ni_sentiment_neutral_grey);
        nature.selected = res.getDrawable(R.drawable.ni_sentiment_neutral_white);
        difficultyMapping.put(R.id.training_neutral, nature);

        TrainingDifficulty satisfied = TrainingDifficulty.satisfied();
        satisfied.drawable = res.getDrawable(R.drawable.ni_sentiment_satisfied_grey);
        satisfied.selected = res.getDrawable(R.drawable.ni_sentiment_satisfied_white);
        difficultyMapping.put(R.id.training_satisfied, satisfied);

        TrainingDifficulty dissatisfied = TrainingDifficulty.dissatisfied();
        dissatisfied.drawable = res.getDrawable(R.drawable.ni_sentiment_dissatisfied_grey);
        dissatisfied.selected = res.getDrawable(R.drawable.ni_sentiment_dissatisfied_white);
        difficultyMapping.put(R.id.training_dissatisfied, dissatisfied);

        trainingDifficulty = difficultyMapping.get(R.id.training_neutral);
    }

    private void initView() {
        movesFlagImg = findViewById(R.id.moves_flag_img);

        trainingNeutral = findViewById(R.id.training_neutral);
        trainingSatisfied = findViewById(R.id.training_satisfied);
        trainingDissatisfied = findViewById(R.id.training_dissatisfied);

        movesName = findViewById(R.id.moves_name);
        trainingPart = findViewById(R.id.training_part);
        trainingThoughts = findViewById(R.id.training_thoughts);
        trainingUsedTime = findViewById(R.id.training_used_time);
        trainingTotalTimes = findViewById(R.id.training_total_times);
        trainingTotalGroups = findViewById(R.id.training_total_groups);

        isWarmUpTraining = findViewById(R.id.is_warm_up_training);
    }

    private void renderView() {
        movesName.setText(move.getTitle());
        movesFlagImg.setImageBitmap(move.getFlagImg());

        trainingPart.setText(move.getTraining().getPart());

        trainingTotalTimes.setText(String.valueOf(standard.getTimes()));
        trainingTotalGroups.setText(String.valueOf(standard.getGroups()));


        trainingUsedTime.setText(MessageFormat.format("{0}分钟", usedTime));
    }

    private void initEvent() {
        View.OnClickListener difficultySelected = view -> {
            for (Map.Entry<Integer, TrainingDifficulty> entry : difficultyMapping.entrySet()) {
                ((ImageView) findViewById(entry.getKey()))
                        .setImageDrawable(entry.getValue().drawable);
            }

            if (difficultyMapping.containsKey(view.getId())) {
                trainingDifficulty = difficultyMapping.get(view.getId());
            }

            trainingThoughts.setText(trainingDifficulty.text);
            ((ImageView) view).setImageDrawable(trainingDifficulty.selected);
        };

        trainingNeutral.setOnClickListener(difficultySelected);
        trainingSatisfied.setOnClickListener(difficultySelected);
        trainingDissatisfied.setOnClickListener(difficultySelected);


        // 推出事件
        findViewById(R.id.exit).setOnClickListener(view -> callBack());
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        return super.keyToBack(keyCode, event);
    }

    @Override
    protected void callBack() {
        saveTrainingData();


        // 是否为热身
        if (isWarmUpTraining.isChecked()) {
            // to 十式 page
            Intent intent = new Intent(this, MovesActivity.class);
            intent.putExtra(Constant.EXTRA_CHAPTER_ID, move.getChapterId());
            startActivity(intent);
        } else {
            // to 六艺 page
            toActivity(IndexActivity.class);
        }
    }

    private void saveTrainingData() {
        final TrainingRecord record = new TrainingRecord();

        record.setDate(new Date());
        record.setUsedTime(usedTime);

        record.setMovesId(move.getId());
        record.setChapterId(move.getChapterId());
        record.setDifficulty(trainingDifficulty.value);

        record.setIsWarmUpTraining(isWarmUpTraining.isChecked());

        record.setStandard(standard);

        Log.i("saveTrainingRecord", record.toString());


        if (!TrainingRecordService.ME.save(record)) {
            ToastUtil.showText(this, "保存训练记录失败！");
        }
    }


    private static class TrainingDifficulty {
        private static final int TRAINING_NEUTRAL = 1;
        private static final int TRAINING_SATISFIED = 0;
        private static final int TRAINING_DISSATISFIED = 2;

        // <!-- 太轻松了，求虐!   感觉还可以!  好累啊，求饶!  -->
        private static final String TRAINING_NEUTRAL_TEXT = "感觉还可以!";
        private static final String TRAINING_SATISFIED_TEXT = "太轻松了，求虐!";
        private static final String TRAINING_DISSATISFIED_TEXT = "好累啊，求饶!";

        final int value;
        final String text;
        Drawable drawable;
        Drawable selected;


        private TrainingDifficulty(int value, @NotNull String text) {
            this.value = value;
            this.text = text;
        }



        public static TrainingDifficulty nature() {
            return new TrainingDifficulty(TRAINING_NEUTRAL, TRAINING_NEUTRAL_TEXT);
        }

        public static TrainingDifficulty satisfied() {
            return new TrainingDifficulty(TRAINING_SATISFIED, TRAINING_SATISFIED_TEXT);
        }

        public static TrainingDifficulty dissatisfied() {
            return new TrainingDifficulty(TRAINING_DISSATISFIED, TRAINING_DISSATISFIED_TEXT);
        }
    }

}